package com.weixing.mall.provider.controller.act;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.enums.SortOrderEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.provider.api.service.ItemFeign;
import com.weixing.mall.provider.model.domain.Activity;
import com.weixing.mall.provider.model.domain.ActivityGoods;
import com.weixing.mall.provider.model.domain.ProductStockTmp;
import com.weixing.mall.provider.model.dto.act.ActivityGoodsDto;
import com.weixing.mall.provider.model.enums.act.IsPublish;
import com.weixing.mall.provider.model.enums.act.UpOrDownEnum;
import com.weixing.mall.provider.model.query.act.ActGoodsAddQuery;
import com.weixing.mall.provider.model.query.act.ActGoodsQuery;
import com.weixing.mall.provider.model.query.act.ProductStockTmpQuery;
import com.weixing.mall.provider.model.vo.excel.ActivityGoodsED;
import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.provider.service.IActivityService;
import com.weixing.mall.provider.service.IProductStockTmpService;
import com.weixing.mall.provider.support.excel.EasyExcelUtil;
import com.weixing.mall.provider.support.excel.act.ActGoodsImportData;
import com.weixing.mall.provider.support.excel.act.ActGoodsImportDataListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ActivityGoodsController
 * @Description 活动关联商品控制类
 * @Author Small
 * @Date 2019/10/23 17:33
 * @Version 1.0
 **/
@RestController
@RequestMapping("act/goods")
@Api(value = "活动关联商品模块API", tags = "活动关联商品")
public class ActivityGoodsController extends BaseController {
    @Autowired
    private IActivityGoodsService activityGoodsService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IProductStockTmpService productStockTmpService;
    @Autowired
    private ItemFeign itemFeign;

    @ApiOperation(value = "加载活动商品列表")
    @GetMapping("")
    @NoNeedAccess
    public Result list(ActGoodsQuery query) {
        activityService.checkIsDown(query);
        IPage pageInfo = activityGoodsService.findList(query, initMpPage());
        return ResultUtil.success(pageInfo);
    }
    @ApiOperation(value = "活动商品批量上架")
    @GetMapping("upQuery")
    @NoNeedAccess
    public Result upAll(ActGoodsQuery query) {
        Long actId=query.getActId();
        Activity activity=activityService.getById(actId);
        if(activity.getEndTime().getTime()-new Date().getTime()<0){
            return ResultUtil.error("活动时间已经结束，不允许上架");
        }
        activityGoodsService.upQuery(query);
        return ResultUtil.success();
    }
    @ApiOperation(value = "活动商品批量上架")
    @GetMapping("dowmQuery")
    @NoNeedAccess
    public Result dowmQuery(ActGoodsQuery query) {
        activityGoodsService.downQuery(query);
        return ResultUtil.success();
    }
    @ApiOperation(value = "加载活动商品库存总数")
    @GetMapping("totalNum")
    public Result totalNum(ActGoodsQuery query) {
        return ResultUtil.success(activityGoodsService.findListTotalNum(query));
    }

    @ApiOperation(value = "加载活动商品列表")
    @GetMapping("listExcel")
    public void listExcel(ActGoodsQuery query, HttpServletResponse response) {
        IPage pageInfo = activityGoodsService.findList(query, initMpPage());
        List<ActivityGoodsED> target = Lists.newArrayList();
        pageInfo.getRecords().forEach( s ->{
            ActivityGoodsED t = new ActivityGoodsED();
            BeanUtils.copyProperties(s,t);
            target.add(t);
        });
        try {
            EasyExcelUtil.writeExcel(response, ActivityGoodsED.class,target,"商品列表");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "加载仓库临时活动商品列表")
    @GetMapping("/tmpDepot")
    public Result list(ProductStockTmpQuery query) {
        IPage pageInfo = productStockTmpService.selectOfPage(initMPage(),query);
        return ResultUtil.success(pageInfo);
    }
    @ApiOperation(value = "仓库商品转到活动商品中")
    @GetMapping("/getDepotList")
    public  Result getDepotList(ProductStockTmpQuery query){
        productStockTmpService.selectByQuery(query);

        return ResultUtil.success();
    }


    @ApiOperation(value = "新增活动商品")
    @PostMapping("add")
    @NoRepeatSubmit
    public Result addSingle(@RequestBody ActivityGoodsDto activityGoodsDto) {
        Activity activity = activityService.getById(activityGoodsDto.getActId());
        if (null == activity) {
            return ResultUtil.error("活动不存在");
        }
        activityGoodsService.addGoods(activity, activityGoodsDto.getProducts());
        return ResultUtil.success();
    }

    @ApiOperation(value = "从仓库中查询新增商品")
    @PostMapping("addList/{depotId}")
    @NoRepeatSubmit
    public Result addList(@PathVariable Long depotId) {
        return ResultUtil.success(productStockTmpService.selectByDepotId(initMpPage(), depotId));
    }

    @ApiOperation(value = "临时更新所属仓库和库存")
    @PostMapping("temporarUpdate")
    @NoRepeatSubmit
    public Result temporarUpdate(ProductStockTmp entity) {
        productStockTmpService.updateById(entity);
        return ResultUtil.success();
    }

    @ApiOperation(value = "修改库存,上传ID和productCount")
    @PostMapping("updateStock")
    @NoRepeatSubmit
    public Result temporarUpdate(ActivityGoods entity) {
        activityGoodsService.updateById(entity);
        activityGoodsService.refreshStockInRedis(entity.getId());
        return ResultUtil.success();
    }

    @ApiOperation(value = "多个商品新增至活动商品")
    @PostMapping("addByIds")
    @NoRepeatSubmit
    public Result addByIds(ActGoodsAddQuery actGoodsAddQuery) {
        activityGoodsService.addByIds(actGoodsAddQuery.getIds(), actGoodsAddQuery.getActId());
        //刷新缓存
        activityService.refreshStockInRedis(actGoodsAddQuery.getActId());
        return ResultUtil.success();
    }

    @ApiOperation(value = "整个仓库商品新增至活动商品")
    @PostMapping("addByWholeDepot/{depotId}/{actId}")
    @NoRepeatSubmit
    public Result addByWholeDepot(@PathVariable Long depotId, @PathVariable Long actId) {
        activityGoodsService.addByWholeDepot(depotId, actId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "重置库存，用于更新仓库数据至临时仓库表")
    @PostMapping("resetStock/{depotId}")
    @NoRepeatSubmit
    public Result resetStock(@PathVariable Long depotId) {
        productStockTmpService.resetStock(depotId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "删除活动商品")
    @PostMapping("del/{ids}")
    public Result del(@PathVariable Long[] ids) {
        activityGoodsService.removeByIds(Lists.newArrayList(ids));
        return ResultUtil.success();
    }

    @ApiOperation(value = "上架商品")
    @PostMapping("up/{ids}")
    @NoNeedAccess
    public Result up(@PathVariable long[] ids) {
        activityGoodsService.upOrDown(ids, UpOrDownEnum.UP.getValue());
        return ResultUtil.success();
    }

    @ApiOperation(value = "下架商品")
    @PostMapping("down/{ids}")
    @NoNeedAccess
    public Result down(@PathVariable long[] ids) {
        activityGoodsService.upOrDown(ids, UpOrDownEnum.DOWM.getValue());
        return ResultUtil.success();
    }


    @ApiOperation(value = "排序规则")
    @PostMapping("sortOrderList")
    public Result sortOrderList() {
        return ResultUtil.success(SortOrderEnum.values());
    }

    @ApiOperation(value = "进行排序")
    @PostMapping("sortOrder")
    public Result sortOrder(ActGoodsQuery entity) {
        Long actId = entity.getActId();
        Activity activity = activityService.getById(actId);
        if (activity.getIsPublish().equals(IsPublish.NOT_PUBLISH)) {
            return ResultUtil.error("未发布不允许排序");
        }
        Date tmp = new Date();
        if (tmp.getTime() > activity.getEndTime().getTime()) {
            return ResultUtil.error("已失效的活动不允许排序");
        }
        activityGoodsService.sortOrder(entity);
        return ResultUtil.success();
    }


    @ApiOperation(value = "变更商品库存后将新库存刷进redis")
    @PostMapping("refreshStockInRedis/{id}")
    public Result refreshStockInRedis(@PathVariable Long id) {
        activityGoodsService.refreshStockInRedis(id);
        return ResultUtil.success();
    }

    @ApiOperation(value = "新增活动-excel导入")
    @PostMapping("importActGoods/{actId}")
    public Result importActGoods(MultipartFile file, @PathVariable Long actId) {
        try {
            EasyExcel.read(file.getInputStream(), ActGoodsImportData.class, new ActGoodsImportDataListener(activityGoodsService, itemFeign, actId)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        activityService.refreshStockInRedis(actId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "仓库导入")
    @PostMapping("depotImprot")
    public Result depotImprot() {
        return ResultUtil.success(SortOrderEnum.values());
    }
}
